const Koa = require('koa')
const Router = require('koa-router')

const port = parseInt(process.env.PORT, 10) || 3003
const dev = process.env.NODE_ENV !== 'production'

const { createServer } = require('http')
const { parse } = require('url')
const next = require('next')
const mobxReact = require('mobx-react')
const app = next({ dev })
const handle = app.getRequestHandler()

mobxReact.useStaticRendering(true)

app.prepare().then(() => {
  const server = new Koa()
  const router = new Router()
  router.get('/day/:date', async ctx => {
    dev && console.log( ctx.params, ctx.query )
    dev && console.log('----------------------------------------------')
    await app.render(ctx.req, ctx.res, '/day', Object.assign(ctx.params, ctx.query))
    ctx.respond = false
  })

  router.get('/detail/:id', async ctx => {
    dev && console.log( ctx.params, ctx.query )
    dev && console.log('----------------------------------------------')
    await app.render(ctx.req, ctx.res, '/detail', Object.assign(ctx.params, ctx.query))
    ctx.respond = false
  })

  router.get('/m/day/:date', async ctx => {
    dev && console.log( ctx.params, ctx.query )
    dev && console.log('----------------------------------------------')
    await app.render(ctx.req, ctx.res, '/m/day', Object.assign(ctx.params, ctx.query))
    ctx.respond = false
  })

  router.get('*', async ctx => {
    const parsedUrl = parse(ctx.url, true)
    const { pathname, query } = parsedUrl

    const ua = ctx.headers['user-agent']

    if (/Mobile/i.test(ua) && pathname.indexOf('/m') === -1) {
      await app.render(ctx.req, ctx.res, `/m${pathname}`, query)
    } else if (!/Mobile/i.test(ua) && pathname.indexOf('/m/') > -1) {
      await app.render(ctx.req, ctx.res, pathname.slice(2), query)
    } else if (!/Mobile/i.test(ua) && pathname.indexOf('/m') > -1) {
      await app.render(ctx.req, ctx.res, '/', query)
    } else {
      await handle(ctx.req, ctx.res, parsedUrl)
    }
    ctx.respond = false
  })

  server.use(async (ctx, next) => {
    ctx.res.statusCode = 200
    await next()
  })

  server.use(router.routes())

  server.listen(port, (err) => {
    if (err) throw err
    console.log(`> Ready on http://localhost:${port}`)
  })

  // createServer((req, res) => {
  //   const parsedUrl = parse(req.url, true)
  //   const { pathname, query } = parsedUrl

  //   const ua = req.headers['user-agent']

  //   if (/Mobile/i.test(ua) && pathname.indexOf('/m') === -1) {
  //     app.render(req, res, `/m${pathname}`, query)
  //   } else if (!/Mobile/i.test(ua) && pathname.indexOf('/m/') > -1) {
  //     app.render(req, res, pathname.slice(2), query)
  //   } else if (!/Mobile/i.test(ua) && pathname.indexOf('/m') > -1) {
  //     app.render(req, res, '/', query)
  //   } else {
  //     handle(req, res, parsedUrl)
  //   }
  // }).listen(port, err => {
  //   if (err) throw err
  //   console.log(`> Ready on http://localhost:${port}`)
  // })
})
